package controller.v2;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import listener.WebContextListener;
import model.CityVO;
import model.MemberVO;
import service.v2.CityService;
import service.v2.ConfigService;
import service.v2.MemberService;
import service.v2.SmsService;
import util.EncryptUtils;
import util.IPUtil;
import util.MD5Util;
import util.NumberUtil;
import util.OssUtil;
import util.PackageUtil;
import util.PropertieUtil;
import util.SmsSendUtil;

@Controller
@RequestMapping("/v2/security")
public class SecurityController {
	@Autowired
	private MemberService memberService;
	@Autowired
	private SmsService smsService;
	@Autowired
	private CityService cityService;
	@Autowired
	private ConfigService configService;
	/**
	 * @param token
	 *            令牌
	 * @param member_id
	 *            用户ID
	 * @return 用户信息 type 4 修改原手机号 5 支付宝密码 6新手机号
	 * 国家代码未处理  6的时候传参数  4和5读取登录信息中代码
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/modifySmsSend", method = RequestMethod.GET)
	public Object memberInfo(@RequestHeader (value="LANG", required=false) String lang,@RequestHeader(value = "AUTHORIZATION", required = false) String token,
			@RequestHeader(value = "SECRET", required = false) String member_id, HttpServletRequest request,
			HttpServletResponse response, MemberVO memberVO, String type) throws Exception {
		//登录的vo
		MemberVO vo = memberService.getLoginMemberById(member_id);
		//类型
		if(type == null){
			return PackageUtil.packageParams(10001,"缺少必选参数","",""); 
		}
		if(!"4".equals(type) && !"5".equals(type) && !"6".equals(type)){
			return PackageUtil.packageParams(10000,"参数错误，请参考API文档","",""); 
		}
		//验证手机号码
		if("6".equals(type)){
			//验证国家
			if(memberVO.getCountry()==null && memberVO.getCountry_id()==null ){
				return PackageUtil.packageParams(10001,PropertieUtil.loadLangPropertie(lang, 10001+""),"",""); 
			}
			//旧版本
			if(memberVO.getCountry()!=null){
				CityVO cityVO = cityService.getCountryByAreaCode(memberVO.getCountry());
				if(cityVO == null){
					return PackageUtil.packageParams(1017,PropertieUtil.loadLangPropertie(lang, 1017+""),"",""); 
				}else{
					memberVO.setCountry_id(cityVO.getId());
					memberVO.setCountry_code(cityVO.getArea_code());
				}
			}
			//新版本
			if(memberVO.getCountry_id() != null){
				CityVO cityVO = cityService.getCityById(memberVO.getCountry_id());
				if(cityVO == null){
					return PackageUtil.packageParams(1017,PropertieUtil.loadLangPropertie(lang, 1017+""),"",""); 
				}else{
					memberVO.setCountry_id(cityVO.getId());
					memberVO.setCountry_code(cityVO.getArea_code());
				}
			}
			//验证电话
			String tel = memberVO.getTel();
			if(tel == null || "".equals(tel.trim())){
				return PackageUtil.packageParams(10001,"缺少必选参数","","");
			}
			if("+86".equals(memberVO.getCountry()) && tel.length() != 11){
				return PackageUtil.packageParams(10701,"手机号码格式错误","","");
			}
//			if(!NumberUtil.isPhoneNumber(tel)   && !tel.startsWith("666")){			 
//				return PackageUtil.packageParams(10701,"手机号码格式错误","",""); 
//			}
			MemberVO member = memberService.getMemberByTelAndCountry(memberVO);
			if(member!=null){
				return PackageUtil.packageParams(10702,"该手机号已注册","",""); 
			}
		}
		String tel = null;
		String country = null;
		//4.5用登录的电话接收
		if("4".equals(type) || "5".equals(type)){
			tel = vo.getTel();
			CityVO cityVO = cityService.getCityById(vo.getCountry_id());
			country = cityVO.getArea_code();
		}
		//6用传的电话接收
		if("6".equals(type)){
			tel = memberVO.getTel();
			country = memberVO.getCountry_code();
		}
		
		// 验证短信相关
		String ip = IPUtil.getIP(request);
		int todaySms = smsService.checkTodayNum(ip, Integer.parseInt(type), memberVO.getCountry_code()+tel);
		if (todaySms > 10) {
			return PackageUtil.packageParams(1011, "您的请求数量已达上线，请24小时后再试！", "", "");
		}
		int num = smsService.checkSmsNoTime(ip, Integer.parseInt(type), memberVO.getCountry_code()+tel);
		if (num == 1) {
			return PackageUtil.packageParams(1016, "验证码发送间隔过短，请稍后再试", "", "");
		}
		int hourNum = smsService.checkHourNum(ip,Integer.parseInt(type), memberVO.getCountry_code()+tel);
		if(hourNum > 5){
			return PackageUtil.packageParams(1018,PropertieUtil.loadLangPropertie(lang, 1018+""),"",""); 
		}
		
		if (tel.startsWith("666")) {
			// 记录验证码
			smsService.insertSmsLog(ip, "123456", country+tel, Integer.parseInt(type));
			Map map = new HashMap();
			String sms_no = EncryptUtils.encodeSHAString("123456"+configService.loadConfig("SMS_SHA"));
			map.put("sms_no", sms_no);
			return PackageUtil.packageParams(200, "success", map, "");
		} else {
			// 调用短信接口
			// 验证码发送失败返回 判断
			String sms_no = SmsSendUtil.sendSms(tel, country);
			if (sms_no != null) {
				// 记录验证码
				smsService.insertSmsLog(ip, sms_no, country+tel, Integer.parseInt(type));
				if("4".equals(type) || "5".equals(type)){
					Map map = new HashMap();
					sms_no = EncryptUtils.encodeSHAString(sms_no+configService.loadConfig("SMS_SHA"));
					map.put("sms_no", sms_no);
					return PackageUtil.packageParams(200, "success", map, "");
				}
				return PackageUtil.packageParams(200, "success", "", "");
			} else {
				return PackageUtil.packageParams(1015, "验证码发送失败", "", "");
			}
		}
	}
	
	/**
	 * 原手机号码 验证码 验证
	 * @param token  令牌
	 * @param member_id  用户ID
	 *             sms_no  验证码
	 *             type 	验证码类型4 修改手机号 5 支付密码
	 */			
	@ResponseBody
	@RequestMapping(value = "/modifyTelCheck", method = RequestMethod.GET)
	public Object modifyTelCheck(@RequestHeader(value = "AUTHORIZATION", required = false) String token,
			@RequestHeader(value = "SECRET", required = false) String member_id, HttpServletRequest request,
			HttpServletResponse response, MemberVO memberVO, String type) {
		MemberVO vo = memberService.getLoginMemberById(member_id);
		//验证码检查
		if (memberVO.getSms_no() == null) {
			return PackageUtil.packageParams(1012, "请输入验证码", "", "");
		}
		if (memberVO.getSms_no().length() != 6) {
			return PackageUtil.packageParams(1013, "验证码格式错误", "", "");
		}
		if(type==null){
			type= "4";
		}
		// 验证码超时
		memberVO.setIp(IPUtil.getIP(request));
		memberVO.setTel(vo.getTel());
		memberVO.setType(type);
		memberVO.setCountry_code(vo.getCountry());
		int num = smsService.checkSmsNoOutTime(memberVO);
		if (num > 0) {
			return PackageUtil.packageParams(1014, "验证码失效，请重新获取验证码", "", "");
		}
		//查询验证码是否正确 检查之前的手机号上的验证码
		int re = smsService.checkSmsReg(memberVO);
		if(re==0){
			return PackageUtil.packageParams(1013,"验证码错误","",""); 
		}else{
				return PackageUtil.packageParams(200,"success","",""); 
		}
	}

	/**
	 * 修改手机号码提交
	 * @param token  令牌
	 * @param member_id  用户ID
	 * @param tel  手机号
	 *             country  国家area_code
	 *             sms_no  验证码
	 *  			member_id  用户ID
	 *  			primary_sms_no
	 * @return 用户信息 
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/modifyTelSub", method = RequestMethod.POST)
	public Object modifyTelSub(@RequestHeader (value="LANG", required=false) String lang,@RequestHeader(value = "AUTHORIZATION", required = false) String token,
			@RequestHeader(value = "SECRET", required = false) String member_id, HttpServletRequest request,
			HttpServletResponse response, MemberVO memberVO, String tel, String primary_sms_no) throws Exception {
		
		MemberVO vo = memberService.getLoginMemberById(member_id);
		//验证国家
		if(memberVO.getCountry()==null && memberVO.getCountry_id()==null ){
			return PackageUtil.packageParams(10001,PropertieUtil.loadLangPropertie(lang, 10001+""),"",""); 
		}
		//旧版本
		if(memberVO.getCountry()!=null){
			CityVO cityVO = cityService.getCountryByAreaCode(memberVO.getCountry());
			if(cityVO == null){
				return PackageUtil.packageParams(1017,PropertieUtil.loadLangPropertie(lang, 1017+""),"",""); 
			}else{
				memberVO.setCountry_id(cityVO.getId());
				memberVO.setCountry_code(cityVO.getArea_code());
			}
		}
		//新版本
		if(memberVO.getCountry_id() != null){
			CityVO cityVO = cityService.getCityById(memberVO.getCountry_id());
			if(cityVO == null){
				return PackageUtil.packageParams(1017,PropertieUtil.loadLangPropertie(lang, 1017+""),"",""); 
			}else{
				memberVO.setCountry_id(cityVO.getId());
				memberVO.setCountry_code(cityVO.getArea_code());
			}
		}
		//验证手机号码
		if(tel == null || "".equals(tel.trim())){
			return PackageUtil.packageParams(10000,"参数错误，请参考API文档","",""); 
		}
		if("pe".equals(WebContextListener.env_code)){
			//如果是666的只能绑定666的
			if(vo.getTel().startsWith("666") && !tel.startsWith("666")){
				return PackageUtil.packageParams(10000,"参数错误，请参考API文档","","不可绑定非测试帐号");
			}
			if(!vo.getTel().startsWith("666") && tel.startsWith("666")){
				return PackageUtil.packageParams(10000,"参数错误，请参考API文档","","不可绑定非测试帐号");
			}
		}
		
		/*验证原验证码*/
		//验证码检查
		if (primary_sms_no == null) {
			return PackageUtil.packageParams(1012, "请输入原验证码", "", "");
		}
		if (primary_sms_no.length() != 6) {
			return PackageUtil.packageParams(1013, "原验证码格式错误", "", "");
		}
		// 验证码超时
		vo.setIp(IPUtil.getIP(request));
		vo.setType("4");
		vo.setSms_no(primary_sms_no);
		vo.setCountry_code(vo.getCountry());
		int num_p = smsService.checkSmsNoOutTime(vo);
		if (num_p > 0) {
			return PackageUtil.packageParams(1014,PropertieUtil.loadLangPropertie(lang, 1014+""),"",""); 
		}
		//查询验证码是否正确 检查之前的手机号上的验证码
		int re_p = smsService.checkSmsReg(vo);
		if(re_p==0){
			return PackageUtil.packageParams(1013,PropertieUtil.loadLangPropertie(lang, 1013+""),"",""); 
		}
		
		/*新验证码*/
//		if(!NumberUtil.isPhoneNumber(tel)   && !tel.startsWith("666")){			 
//			return PackageUtil.packageParams(10701,"手机号码格式有误","",""); 
//		}
		//新验证码检查
		if (memberVO.getSms_no() == null) {
			return PackageUtil.packageParams(1012,PropertieUtil.loadLangPropertie(lang, 1012+""),"",""); 
		}
		if (memberVO.getSms_no().length() != 6) {
			return PackageUtil.packageParams(1013,PropertieUtil.loadLangPropertie(lang, 1013+""),"",""); 
		}
		// 验证码超时
		memberVO.setIp(IPUtil.getIP(request));
		memberVO.setType("6");
		int num = smsService.checkSmsNoOutTime(memberVO);
		if (num > 0) {
			return PackageUtil.packageParams(1014,PropertieUtil.loadLangPropertie(lang, 1014+""),"",""); 
		}
		//查询验证码是否正确 
		int re = smsService.checkSmsReg(memberVO);
		if(re==0){
			return PackageUtil.packageParams(1013,PropertieUtil.loadLangPropertie(lang, 1013+""),"",""); 
		}else{
			//判断修改的手机号是否注册
			int telNum = memberService.getMemberCountByTelAndCountry(memberVO);
			if(telNum == 0){
				//修改密码提交
				memberVO.setId(member_id);
				memberService.updateTel(memberVO);
				return PackageUtil.packageParams(200,"绑定成功","",""); 
			}else{
				return PackageUtil.packageParams(10702,PropertieUtil.loadLangPropertie(lang, 10702+""),"",""); 
			}
		}
	}
	
	/**
	 * 修改密码
	 * @param token  令牌
	 * @param member_id  用户ID
	 * @param pwd  原密码
	 *  @param new_pwd 新密码
	 */
	@ResponseBody
	@RequestMapping(value = "/modifyPwdSub", method = RequestMethod.POST)
	public Object modifyPwdSub(@RequestHeader (value="LANG", required=false) String lang,@RequestHeader(value = "AUTHORIZATION", required = false) String token,
			@RequestHeader(value = "SECRET", required = false) String member_id, HttpServletRequest request,
			HttpServletResponse response, MemberVO memberVO, String new_pwd) {
		//验证密码
		if(memberVO.getPwd()==null || memberVO.getPwd().length() != 32){
			return PackageUtil.packageParams(10705,"请输入原密码","",""); 
		}
		if(new_pwd==null || new_pwd.length() != 32){
			return PackageUtil.packageParams(10705,"请输入新密码","",""); 
		}
		//验证原密码是否正确
		memberVO.setId(member_id);
		int num = memberService.checkPwd(memberVO);
		if(num==0){
			return PackageUtil.packageParams(13005,PropertieUtil.loadLangPropertie(lang, 13005+""),"",""); 
		}
		if(memberVO.getPwd().equals(new_pwd)){
			return PackageUtil.packageParams(10711,PropertieUtil.loadLangPropertie(lang, 10711+""),"",""); 
		}
		//修改密码
		memberVO.setPwd(new_pwd);
		memberService.updatePwdById(memberVO);
		return PackageUtil.packageParams(200,"设置成功","",""); 
	}
	
	/**
	 * 修改支付密码
	 * @param token  令牌
	 * @param member_id  用户ID
	 * @param pay_pwd  密码
	 * @param sms_no  验证码
	 * @param tel  手机号
	 */
	@ResponseBody
	@RequestMapping(value = "/modifyPayPwdSub", method = RequestMethod.POST)
	public Object modifyPayPwdSub(@RequestHeader (value="LANG", required=false) String lang,@RequestHeader(value = "AUTHORIZATION", required = false) String token,
			@RequestHeader(value = "SECRET", required = false) String member_id, HttpServletRequest request,
			HttpServletResponse response, MemberVO memberVO) {
		MemberVO vo = memberService.getLoginMemberById(member_id);
		//验证密码
		if(memberVO.getPay_pwd()==null || memberVO.getPay_pwd().length() != 32){
			return PackageUtil.packageParams(10705,"密码格式错误","",""); 
		}
		memberVO.setTel(vo.getTel());
		// 验证码超时
		memberVO.setIp(IPUtil.getIP(request));
		memberVO.setType("5");
		memberVO.setCountry_code(vo.getCountry());
		int num = smsService.checkSmsNoOutTime(memberVO);
		if (num > 0) {
			return PackageUtil.packageParams(1014,PropertieUtil.loadLangPropertie(lang, 1014+""),"",""); 
		}
		//查询验证码是否正确 
		int re = smsService.checkSmsReg(memberVO);
		if(re==0){
			return PackageUtil.packageParams(1013,PropertieUtil.loadLangPropertie(lang, 1013+""),"",""); 
		}else{
			//修改密码
			memberVO.setId(member_id);
			memberService.updatePayPwdById(memberVO);
			return PackageUtil.packageParams(200,"设置成功","",""); 
		}
	}
	
	
	/**
	 * 城市列表
	 * @param token  令牌
	 * @param member_id  用户ID
	 */
	@ResponseBody
	@RequestMapping(value = "/cityList", method = RequestMethod.GET)
	public Object cityList(@RequestHeader(value = "LANG", required = false) String lang,
			@RequestHeader(value = "AUTHORIZATION", required = false) String token,
			@RequestHeader(value = "SECRET", required = false) String member_id, HttpServletRequest request,
			HttpServletResponse response, MemberVO memberVO) {
		List<CityVO> list = cityService.getCityListAll();
		return PackageUtil.packageParams(200,"success",list,""); 
	}
	
	/**
	 * 城市列表 国际
	 * @param token  令牌
	 * @param member_id  用户ID
	 */
	@ResponseBody
	@RequestMapping(value = "/childCityList", method = RequestMethod.GET)
	public Object cityListEn(@RequestHeader(value = "LANG", required = false) String lang,
			@RequestHeader(value = "AUTHORIZATION", required = false) String token,
			@RequestHeader(value = "SECRET", required = false) String member_id, HttpServletRequest request,
			HttpServletResponse response, MemberVO memberVO,String parent_id) {
		if(parent_id==null){
			return PackageUtil.packageParams(10001,PropertieUtil.loadLangPropertie(lang, 10001+""),"",""); 
		}
		List<CityVO> list = cityService.childCityList(parent_id);
		return PackageUtil.packageParams(200,"success",list,""); 
	}
	

	/**
	 * 实名认证
	 * @param token  令牌
	 * @param member_id  用户ID
	 * idcard_front_img 身份证正面照
	 * idcard_back_img 身份证背面照
	 * name  真实姓名
	 * city 3级城市ID
	 * idcard  身份证号
	 */
	@ResponseBody
	@RequestMapping(value = "/idcardApprove", method = RequestMethod.POST)
	public Object idcardApprove(@RequestHeader(value = "LANG", required = false) String lang,@RequestHeader(value = "AUTHORIZATION", required = false) String token,
			@RequestHeader(value = "SECRET", required = false) String member_id, HttpServletRequest request,
			HttpServletResponse response, MemberVO memberVO) {
		//参数验证
		if(memberVO.getInter_verify_idcard_type()==null ||"".equals(memberVO.getInter_verify_idcard_type())){
			return PackageUtil.packageParams(10000,"参数错误，请参考API文档","",""); 
		}
		if("en".equals(lang) && !"1".equals(memberVO.getInter_verify_idcard_type()) && !"2".equals(memberVO.getInter_verify_idcard_type())){
			return PackageUtil.packageParams(10000,"参数错误，请参考API文档","",""); 
		}
		if(memberVO.getInter_verify_country()==null || "".equals(memberVO.getInter_verify_country())){
			return PackageUtil.packageParams(10000,"参数错误，请参考API文档","",""); 
		}
		if(memberVO.getInter_verify_name()==null || "".equals(memberVO.getInter_verify_name())){
			return PackageUtil.packageParams(10000,"参数错误，请参考API文档","",""); 
		}
		if(memberVO.getInter_verify_idcardno()==null || "".equals(memberVO.getInter_verify_idcardno())){
			return PackageUtil.packageParams(10000,"参数错误，请参考API文档","",""); 

		}
		
		CityVO cityVO = cityService.checkInterCityLevelAndId(memberVO.getInter_verify_country());
		if(cityVO == null){
			return PackageUtil.packageParams(10000,"参数错误，请参考API文档","",""); 
		}
		//认证
		memberVO.setId(member_id);
		//memberService.updateIdCardInfo(memberVO);
		memberService.updateInterIdCardInfo(memberVO);
		return PackageUtil.packageParams(200,"success","",""); 
	}
	
	/**
	 * 实名认证状态
	 * @param token  令牌
	 * @param member_id  用户ID
	 */
	@ResponseBody
	@RequestMapping(value = "/idcardInfo", method = RequestMethod.GET)
	public Object idcardInfo(@RequestHeader(value = "AUTHORIZATION", required = false) String token,
			@RequestHeader(value = "SECRET", required = false) String member_id, HttpServletRequest request,
			HttpServletResponse response, MemberVO memberVO) {
		memberVO = memberService.getInterIdcardInfo(member_id);
		return PackageUtil.packageParams(200,"success",memberVO,""); 
	}
	/**
	 * 实名认证 未认证时
	 * @param token  令牌
	 * @param member_id  用户ID
	 * @param name  真实姓名
	 * @param idcard  身份证号
	 */
	@ResponseBody
	@RequestMapping(value = "/newIdcardApprove", method = RequestMethod.POST)
	public Object newIdcardApprove(@RequestHeader(value = "AUTHORIZATION", required = false) String token,
			@RequestHeader(value = "SECRET", required = false) String member_id, HttpServletRequest request,
			HttpServletResponse response, MemberVO memberVO) {
		MemberVO memberOne=memberService.getAllInfoById(member_id);
		if(!"4".equals(memberOne.getIdcard_state())){
			//参数验证
			if (memberVO.getName() == null || "".equals(memberVO.getName()) || memberVO.getName().length() > 30) {
				return PackageUtil.packageParams(10000,"参数错误，请参考API文档","",""); 
			}
			if (memberVO.getIdcard() == null || "".equals(memberVO.getIdcard()) || memberVO.getIdcard().length() > 20) {
				return PackageUtil.packageParams(10000,"参数错误，请参考API文档","",""); 
			}
		}
		memberVO.setId(member_id);
		//实名认证
		JSONObject result = memberService.checkIdcardApprove(memberVO);
		MemberVO vo=memberService.getAllInfoById(memberVO.getId());
		Map<String, Object> map = new HashMap();
		//1 未认证 3 认证失败 4 认证成功
	
		map.put("idcard_state",vo.getIdcard_state());
		map.put("name",vo.getName());
		map.put("idcard",vo.getIdcard());
		map.put("idcard_reason",vo.getIdcard_reason());
		map.put("img_state",vo.getIdcard_front_img()==null?"0":"1");
		
		return PackageUtil.packageParams(200,"success",map,""); 
	}
	/**
	 * 实名认证 已认证时
	 * @param token  令牌
	 * @param member_id  用户ID
	 */
	@ResponseBody
	@RequestMapping(value = "/newIdcardAuthenticated", method = RequestMethod.GET)
	public Object newIdcardAuthenticated(@RequestHeader(value = "AUTHORIZATION", required = false) String token,
			@RequestHeader(value = "SECRET", required = false) String member_id, HttpServletRequest request,
			HttpServletResponse response, MemberVO memberVO) {
		memberVO = memberService.getAllInfoById(member_id);
		
		Map<String, Object> map = new HashMap();
		//1 未认证 3 认证失败 4 认证成功
	
		map.put("idcard_state",memberVO.getIdcard_state());
		map.put("name",memberVO.getName());
		map.put("idcard",memberVO.getIdcard());
		map.put("idcard_reason",memberVO.getIdcard_reason());
		map.put("img_state",memberVO.getIdcard_front_img()==null?"0":"1");
		return PackageUtil.packageParams(200,"success",map,""); 
	}
	
	/**
	 *微信端实名认证上传头像
	 */
	@ResponseBody
	@RequestMapping(value = "/idCardUpImg", method = RequestMethod.POST)
	public Object idCardUpImg(@RequestHeader(value = "AUTHORIZATION", required = false) String token,
			@RequestHeader(value = "SECRET", required = false) String member_id, 
			HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
		MemberVO vo= memberService.getAllInfoById(member_id);
		return PackageUtil.packageParams(200,"success",OssUtil.uploadFile(file, "Upload/member/"+vo.getId()+"/idcard/"),""); 
	}
}
